from flask import Flask
from redis import Redis
from wechatpy.session.redisstorage import RedisStorage
import eventlet.wsgi
from app import host, port
from app.routes import Route
from app.routes.android_route import android_route
from app.routes.http_route import wx_http_route
from app.routes.mtk_route import mtk_route
from app.routes.books_route import books_route
from app.routes.test_route import test_route
from app.routes.websocket_route import socketIo
from config.config import redisIp, redisPort
from vendor.python_socketio_master import socketio


def init_route():
    _dict = {}
    for url in wsgi_app.url_map._rules:
        url_arr = str(url).split('/')
        _dict.setdefault(url_arr[1], set())
        _dict[url_arr[1]].add(url_arr[-1])

    redis = Redis(redisIp, redisPort)
    cli = RedisStorage(redis=redis)
    for key in _dict:
        _set = '|' . join(_dict[key])
        cli.set(Route.get_router_saver_key(key), _set)
        redis.publish(Route.get_router_saver_key(key), _set)


if __name__ == '__main__':
    # wrap Flask application with engineio's middleware
    wsgi_app = Flask(__name__)

    # wsgi_app.config.from_object(config[config_name])
    # config[config_name].init_app(app)

    routers = (test_route, wx_http_route, mtk_route, android_route, books_route)
    for router in routers:
        print('/' + router.name)
        wsgi_app.register_blueprint(router, url_prefix='/' + router.name)

    init_route()

    app = socketio.Middleware(socketIo, wsgi_app)
    # deploy as an eventlet WSGI server
    eventlet.wsgi.server(eventlet.listen((host, port)), app)

